﻿using VictorBlaga.DocumentManagement.Core.Models;
using VictorBlaga.DocumentManagement.Models;
using VictorBlaga.DocumentManagement.Core.Services;
using VictorBlaga.DocumentManagement.Infrastructure;
using VictorBlaga.DocumentManagement.Core.Models.Repositories;

namespace VictorBlaga.DocumentManagement.Helpers.Mappers.Impl
{
    public class UserMapper : IUserMapper
    {
        readonly IWorkshopRepository _workshopRepository;
        readonly ICryptographerService _cryptoService;

        public UserMapper(IWorkshopRepository workshopRepository, ICryptographerService cryptoService)
        {
            _workshopRepository = workshopRepository;
            _cryptoService = cryptoService;
        }

        public UserViewModel MapToViewModel(User model)
        {           
            var viewModel = new UserViewModel();
            if (model != null)
            {
                viewModel.Id = model.ID;
                viewModel.Email = model.Email;
                viewModel.Firstname = model.Firstname;
                viewModel.Lastname = model.Lastname;
                viewModel.UserLevel = model.UserLevel;
                viewModel.Username = model.Username;
                if (model.Workshop == null)
                    viewModel.WorkshopID = null;
                else
                    viewModel.WorkshopID = model.Workshop.ID;
            }

            return viewModel;
        }

        public void MapToModel(UserViewModel viewModel, User model)
        {
            model.Firstname = viewModel.Firstname.CapFirstLetter();
            model.Lastname = viewModel.Lastname.CapFirstLetter();
            model.Email = viewModel.Email.ToLower();
            model.Username = viewModel.Username.ToLower();
            model.UserLevel = viewModel.UserLevel;
            if (viewModel.WorkshopID != null)
            {
                model.Workshop = _workshopRepository.GetByID((int)viewModel.WorkshopID);
            }
            else
            {
                model.Workshop = null;
            }

            model.PasswordSalt = _cryptoService.CreateSalt();
            model.PasswordHash = _cryptoService.GetPasswordHash(viewModel.Password, model.PasswordSalt);
        }
    }
}